﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ChinaTokenDev.Logger
{
    /// <summary>
    /// 日志清理类
    /// </summary>
    public class ClearLoger
    {
        private readonly string LogRootDir = "Logs";
        private readonly ILogAdapter Logger = new TxtLogHelper();
        /// <summary>
        /// 清理日志
        /// </summary>
        /// <param name="day">保留天数</param>
        /// <returns></returns>
        public int Clean(int day)
        {
            try
            {
                //1、先罗列出所有目录
                //2、确定哪些目录可以删除
                //DateTime lastDate = DateTime.Now.AddDays(-day);
                DeleteLogFiles(day);
                //string 
                //DeleteDirectory();
                return 0;
            }
            catch (Exception ex)
            {
                WriteLogEx("[ERROR] ", ex.ToString());
                Console.WriteLine(ex.ToString());
                return -1;
            }
        }

        private void WriteLogEx(string type, string msg)
        {
            //string dir = Path.Combine(System.Threading.Thread.GetDomain().BaseDirectory, "Logs", DateTime.Now.ToString("yyyyMM"));
            string dir = Path.Combine(System.Threading.Thread.GetDomain().BaseDirectory, LogRootDir, DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("dd"));
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string fileName = Path.Combine(dir, string.Concat("SysMonitor", ".log"));
            Logger.WriteLogEx(fileName, string.Concat(type, msg));
        }

        /// <summary>
        /// 删除过期日志
        /// </summary>
        /// <param name="day"></param>
        public void DeleteLogFiles(int day)
        {
            try
            {
                //获取日志根目录
                string rootLogs = Path.Combine(System.Threading.Thread.GetDomain().BaseDirectory, LogRootDir);
                List<string> dirs = new List<string>();
                List<string> files = new List<string>();
                List<string> logdirs = new List<string>();

                if (Directory.Exists(rootLogs))
                {
                    dirs.AddRange(Directory.GetDirectories(rootLogs).ToList());
                }
                else
                {
                    return;
                }

                //取得需要删除的文件 未限定文件，只按时间来处理
                foreach (string dir in dirs)
                {
                    //系统当前时间和文件创建时间进行比价
                    files.AddRange(Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Where(o => (System.DateTime.Now - (new FileInfo(o).CreationTime)).Days >= day));
                }

                if (files.Count > 0)
                {
                    WriteLogEx("[DEBUG] ", string.Format("共有{0}个文件等待删除", files.Count));
                    //进行文件删除
                    foreach (var item in files)
                    {
                        Console.WriteLine(item);
                        File.Delete(item);
                    }
                }
                //删除空目录
                logdirs.Clear();
                //根目录下可删除的目录
                logdirs.AddRange(Directory.GetDirectories(rootLogs, "*", SearchOption.AllDirectories).Where(t => Directory.GetFiles(t).ToList().Count == 0 && Directory.GetDirectories(t).ToList().Count == 0).ToList());
                //foreach (var item in dirs)
                //{
                    ////子目录没有文件和子目录的可以进行删除
                    //logdirs.AddRange(Directory.GetDirectories(item).Where(t => Directory.GetFiles(t).ToList().Count == 0 && Directory.GetDirectories(t).ToList().Count == 0).ToList());
                //}
                
                WriteLogEx("[DEBUG] ", string.Format("共有{0}个目录等待删除", logdirs.Count));
                foreach (var item in logdirs)
                {
                    WriteLogEx("[DEBUG] ", string.Format("正在删除日志目录{0}", item));
                    Directory.Delete(item, true);
                }
            }
            catch (Exception ex)
            {
                WriteLogEx("[ERROR] ", ex.ToString());
                Console.WriteLine(ex.ToString());
            }
            
        }

        /// <summary>
        /// 获取目录中指定类型文件列表
        /// </summary>
        /// <param name="nowDirName">目录全路径</param>
        /// <param name="bSubDir">是否包括子目录文件</param>
        /// <param name="nowFileType">文件类型</param>
        /// <returns></returns>
        public List<string> ListDirFiles(string nowDirName, bool bSubDir, params string[] nowFileType)
        {
            try
            {
                List<string> tmpList = new List<string>();
                if (!Directory.Exists(nowDirName))
                {
                    return null;
                }
                if (nowFileType != null && nowFileType.Length > 0)
                {
                    string ftype = @"*." + nowFileType[0].ToLower().ToString();
                    string[] fLists = Directory.GetFiles(nowDirName, ftype);
                    var flist = Directory.GetFiles(nowDirName, ftype).Where(t => t.ToLower().EndsWith(ftype));
                    tmpList = fLists.ToList<string>();
                    //tmpList = flist.ToList<string>();
                }
                else
                {
                    string[] fLists = Directory.GetFiles(nowDirName);
                    tmpList = fLists.ToList<string>();
                }
                return tmpList;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void DeleteDirectory(string directoryPath)
        {
            try
            {
                //第一步：先删除所有文件
                for (int i = 0; i < Directory.GetFiles(directoryPath).ToList().Count; i++)
                {
                    File.Delete(Directory.GetFiles(directoryPath)[i]);
                }

                //第二步：删除文件夹
                for (int i = 0; i < Directory.GetDirectories(directoryPath).ToList().Count; i++)
                {
                    Directory.Delete(Directory.GetDirectories(directoryPath)[i], true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            
        }
    }
}
